import { useRequest } from "../../../utils/request";
import dayjs from '../../../utils/day'
import { add } from "../../../utils/utils";

Component({
    properties: {},
    data: {
        // 显示选择时间
        showChangeTimeStatus: false,
        // 入住时间
        startTime: 0,
        // 退房时间
        endTime: 0,
        // 总天数
        days: 0,
    },
    observers: {
        'peopleData.**': function (data) {
            this.setData({
                changePeopleData: data.filter(item => item.change)
            })
        },
        'startTime,endTime': function (startTime, endTime) {
            this.setData({
                days: dayjs(endTime, 'YYYY-MM-DD').diff(dayjs(startTime, 'YYYY-MM-DD'), 'day'),
            })
        },
        'days': function (data) {
            this.setData({
                totalPrice: add(this.data.houseData.price * data + this.data.houseData.yajin, this.data.houseData.price_clean)
            })
        }
    },
    methods: {
        onLoad() {
            // 获取房源信息
            const eventChannel = this.getOpenerEventChannel()
            eventChannel.on('getHouseData', houseData => {
                this.setData({
                    houseData
                })

                // 初始化入住时间
                this.setData({
                    startTime: dayjs().format('YYYY-MM-DD'),
                    endTime: dayjs().add(1, 'day').format('YYYY-MM-DD')
                })
            })

            // 入住人列表
            this.peopleRequest = new useRequest('api/livepeoplelist', {
                data: 'peopleData',
                loading: 'peopleLoading',
                pretreatment: data => data.list || []
            }, this)

            // 删除入住人
            this.removeRequest = new useRequest('api/deletelivepeople', {
                loading: false,
                hold: true
            }, this)

            // 创建订单
            this.createOrderRequest = new useRequest('api/orderhouse', {
                loading: 'createLoading',
                hold: true,
            }, this)

            // 初始化房源状态 - 梁展超  用于日历底部加字体 的已经被选择的时间戳
            this.initHouseStatus = new useRequest('api/gethousestatus',{
                loading: 'houseStatusLoading',
                hold: true,
                params:{
                    house_id:this.data.houseData.house_id
                }
            }).run().then(res => {
               const {lock_time,live_time} = res
               console.log(lock_time,live_time)
               console.log(typeof lock_time);
               live_time.forEach(element => {
                   if(typeof(element)=='object'){
                       console.log(element);
                   }
               });
               const startTime1= dayjs().format('YYYY-MM-DD')
               const endTime2 =  dayjs().format('YYYY-MM-DD')
            }),
          console.log(this);
        }
        
        // 日历底部加字   
        //   calendarOpen(e){
        //       console.log(e,this.data);
        //       console.log(dayjs());
        //   },

        // 入住时间
        ,
        formatter(e){
            console.log(e);
      
            // const month = day.date.getMonth() + 1;
            // const date = day.date.getDate();
            // console.log(month,date);
    
            // if (month === 5) {
            //   if (date === 1) {
            //     day.topInfo = '劳动节';
            //   } else if (date === 4) {
            //     day.topInfo = '五四青年节';
            //   } else if (date === 11) {
            //     day.text = '今天';
            //   }
            // }
      
            // if (day.type === 'start') {
            //   day.bottomInfo = '入住';
            // } else if (day.type === 'end') {
            //   day.bottomInfo = '离店';
            // }
            // return day;
          },
        changeTime(e) {
            if (dayjs(e.detail[0]).isBefore(dayjs(), 'day')) {
                wx.showToast({
                    title: '不能选择过去的日期',
                    icon: 'none'
                })
                return
            }
            this.setData({
                startTime: dayjs(e.detail[0]).format('YYYY-MM-DD'),
                endTime: dayjs(e.detail[1]).format('YYYY-MM-DD'),
            })
            this.hideChangeTime()
        },
        showChangeTime() {
            this.setData({
                showChangeTimeStatus: true
            })
        },
        hideChangeTime() {
            this.setData({
                showChangeTimeStatus: false
            })
        },

        // 入住人
        changePeople(e) {
            const index = e.currentTarget.dataset.index
            this.setData({
                ['peopleData[' + index + '].change']: !this.data.peopleData[index].change
            })
        },
        removePeople(e) {
            const index = e.currentTarget.dataset.index
            wx.showModal({
                content: '您确定要删除该入住人吗？',
                success: async result => {
                    if (result.confirm) {
                        wx.showLoading({})
                        await this.removeRequest.run({ user_id: this.data.peopleData[index].user_id })
                        const list = this.data.peopleData
                        list.splice(index, 1)
                        this.setData({
                            peopleData: list
                        })
                        wx.hideLoading()
                    }
                }
            })
        },
        editPeople(e) {
            // 选择人的index
            const index = e.currentTarget.dataset.index
            // 所有的人的index
            const dataIndex = this.data.peopleData.findIndex(item => item.user_id === this.data.changePeopleData[index].user_id)
            wx.navigateTo({
                url: '/pages/resident/edit/edit',
                success: result => {
                    result.eventChannel.emit('getEditPeople', this.data.peopleData[dataIndex])
                    result.eventChannel.on('editPeople', data => {
                        this.setData({
                            ['peopleData[' + dataIndex + ']']: {
                                ...data,
                                change: true
                            }
                        })
                    })
                }
            })
        },
        addPeople() {
            wx.navigateTo({
                url: '/pages/resident/edit/edit',
                success: result => {
                    result.eventChannel.on('addPeople', data => {
                        this.setData({
                            peopleData: [...this.data.peopleData, data]
                        })
                    })
                }
            })
        },

        pay() {
            this.createOrderRequest.run({
                house_id: this.data.houseData.house_id,
                start_live_time: dayjs(this.data.startTime, 'YYYY-MM-DD').hour(0).minute(0).second(0).unix(),
                end_live_time: dayjs(this.data.endTime, 'YYYY-MM-DD').hour(0).minute(0).second(0).unix(),
                live_people: this.data.changePeopleData,
                total: this.data.totalPrice,
                live_money: this.data.houseData.price * this.data.days,
                clean_money: this.data.houseData.price_clean,
                yajin: this.data.houseData.yajin
            }).then(data => {
                wx.navigateTo({
                    url: `/pages/order/pay/pay?order=${data.order_no}&price=${data.total}`,
                    success: result => {
                        result.eventChannel.on('toDetail', function () {
                            wx.redirectTo({
                                url: '/pages/order/detail/detail?id=' + data.order_no
                            })
                        })
                    }
                })
            })
        },

        // 创建订单
        createOrder() {
            if (!this.data.changePeopleData.length) {
                wx.showToast({
                    title: '请填写入住人信息',
                    icon: "none"
                })
                return
            }
            if (dayjs(this.data.startTime, 'YYYY-MM-DD').isSame(dayjs(), 'day') && dayjs().hour() >= 14) {
                wx.showModal({
                    title: '提示',
                    content: '入住时间超过14点，若选择退房，将会给您造成损失，请谨慎操作',
                    success: result => {
                        if (result.confirm) {
                            this.pay()
                        }
                    }
                })
            } else {
                this.pay()
            }
        },
    }
});
